import os
import shutil
def process_srt(input_file, output_file):
    """
    处理srt文件，去除时间戳行并保存为新文件

    参数:
    input_file (str): 输入srt文件的路径
    output_file (str): 输出文件的路径
    """
    try:
        with open(input_file, 'r', encoding='utf-8') as f:
            lines = f.readlines()

        # 用于存储处理后的行
        processed_lines = []

        i = 0
        while i < len(lines):
            line = lines[i].strip()

            # 跳过空行
            if not line:
                i += 1
                continue

            # 检查是否为数字编号行（第一行）
            if line.isdigit():
                processed_lines.append(line + '\n')
                i += 1

                # 跳过时间戳行
                if i < len(lines):
                    i += 1

                # 添加字幕内容
                while i < len(lines) and lines[i].strip() != "":
                    processed_lines.append(lines[i])
                    i += 1
            else:
                i += 1

        # 写入新文件
        with open(output_file, 'w', encoding='utf-8') as f:
            f.writelines(processed_lines)

        print(f"处理完成！结果已保存到: {output_file}")

    except Exception as e:
        print(f"处理文件时出错: {str(e)}")


def merge_srt(original_srt, edited_content, output_srt):
    """
    合并原始srt文件和编辑后的内容，生成新的srt文件

    参数:
    original_srt (str): 原始srt文件路径
    edited_content (str): 编辑后的内容文件路径
    output_srt (str): 输出的新srt文件路径
    """
    try:
        # 读取编辑后的内容文件，创建编号到内容的映射
        edited_dict = {}

        with open(edited_content, 'r', encoding='utf-8') as f:
            # 读取所有非空行
            non_empty_lines = [line.strip() for line in f.readlines() if line.strip()]

            # 按奇偶性分组：奇数行(索引为0,2,4...)为编号，偶数行为内容
            for i in range(0, len(non_empty_lines), 2):
                if i + 1 < len(non_empty_lines):  # 确保有内容行
                    number = non_empty_lines[i]
                    content = non_empty_lines[i + 1]
                    edited_dict[number] = [content]

        # 读取原始srt文件
        with open(original_srt, 'r', encoding='utf-8') as f:
            lines = f.readlines()

        # 处理和写入新文件
        new_lines = []
        i = 0
        prev_line_empty = True  # 文件开始视为空行

        while i < len(lines):
            line = lines[i].strip()

            # 判断是否为编号行：上一行为空且当前行为数字
            is_number_line = prev_line_empty and line.isdigit()

            # 更新prev_line_empty状态
            prev_line_empty = (line == "")

            if is_number_line:
                number = line
                new_lines.append(line + '\n')  # 添加编号
                i += 1

                # 添加时间戳行
                if i < len(lines):
                    new_lines.append(lines[i])  # 保持原有的时间戳
                    i += 1

                # 添加新的内容
                if number in edited_dict:
                    for content_line in edited_dict[number]:
                        new_lines.append(content_line + '\n')

                # 添加空行
                new_lines.append('\n')

                # 跳过原内容直到空行
                while i < len(lines) and lines[i].strip() != "":
                    i += 1
            else:
                if line == "":
                    new_lines.append('\n')
                i += 1

        # 写入新文件
        with open(output_srt, 'w', encoding='utf-8') as f:
            f.writelines(new_lines)

        print(f"合并完成！新的srt文件已保存到: {output_srt}")

    except Exception as e:
        print(f"合并文件时出错: {str(e)}")
        

# 使用示例
if __name__ == "__main__":
    # 第一步：处理原始srt文件
    input_file = "C:\\Users\\X\\Desktop\\字幕\\src.srt"
    output_file = "C:\\Users\\X\\Desktop\\字幕\\out.zm"

    # 第二步：合并处理后的文件与原始srt
    edited_file = "C:\\Users\\X\\Desktop\\字幕\\out.zm"  # 这是已经手动编辑过的文件
    final_srt = "C:\\Users\\X\\Desktop\\字幕\\new.srt"  # 这是最终输出的新srt文件

    # 获取当前目录下所有文件
    current_dir = os.path.abspath('.\\zm')  # 获取当前目录的绝对路径

    for filename in os.listdir(current_dir):
        print(f"文件名: {filename}")
        # 检查文件是否以.zm结尾
        if filename.endswith('.zm'):
            # 获取文件的绝对路径
            full_path = os.path.join(current_dir, filename)
            if os.path.getsize(full_path) > 0:
                name_without_ext = os.path.splitext(filename)[0]
                print(f"绝对路径: {full_path}")
                merge_srt(input_file, full_path, f"C:\\Users\\X\\Desktop\\字幕\\srt\\{name_without_ext}.srt")
    shutil.copy('src.srt', 'srt/en.srt')
    os.system("pause")
